#coding=utf-8
#LightCam snmptrap服务程序
#init by hfh 20160122

import socket,os,time,re,subprocess,multiprocessing,traceback,lc_libs,sys
import SocketServer,gc

#class LCSocketServer(SocketServer.ThreadingTCPServer):
#	def __init__(self,ADDR,LCAgent):
#		SocketServer.ThreadingTCPServer.__init__(self,ADDR,LCAgent)
		
	#def InitArgvs(self,agent_hostname,AgentList):
	#	self.BUFSIZ=8192
	#	self.s={}
	#	self.agent_hostname=agent_hostname
	#	self.AgentList=AgentList
	#	print self.agent_hostname
	#	print self.AgentList
		


#class LCAgent(SocketServer.StreamRequestHandler):
class LCAgent(SocketServer.DatagramRequestHandler):
	
	def handle(self):
		
		global BUFSIZ
		
		try:
			#print dir(self)
			#['__doc__', '__init__', '__module__', 'client_address', 'finish', 'handle', 'packet', 'request', 'rfile', 'server', 'setup', 'socket', 'wfile']
			
			#print dir(self.server)
			#['RequestHandlerClass', '_BaseServer__is_shut_down', '_BaseServer__shutdown_request', '__doc__', '__init__', '__module__', '_handle_request_noblock', 'address_family', 'allow_reuse_address', 'close_request', 'daemon_threads', 'fileno', 'finish_request', 'get_request', 'handle_error', 'handle_request', 'handle_timeout', 'max_packet_size', 'process_request', 'process_request_thread', 'request_queue_size', 'serve_forever', 'server_activate', 'server_address', 'server_bind', 'server_close', 'shutdown', 'shutdown_request', 'socket', 'socket_type', 'timeout', 'verify_request']
			print "Data received from %s:%s " % self.client_address[:]

			print self.__doc__
			print self.__init__
			print self.__module__
			print self.client_address
			print self.finish
			print self.handle
			print self.packet
			print self.request
			print self.rfile
			print self.server
			print self.setup
			print self.socket
			print self.wfile

			
			#return 0
			
			#recv_data = self.request.recv(BUFSIZ)
			#data, client_addr = self.socket.recvfrom(BUFSIZ)
			#client_addr = self.request.getpeername()
			recv_data = self.rfile.read(BUFSIZ)
			
			print "---------------Start of Data---------------\n"
			print recv_data
			print "---------------End of Data---------------\n"
			print "---------------Start of Data ASCII---------------\n"
			strs=''
			for i in recv_data:
				ordvalue=ord(i)
				res=lc_libs.lc_genacsii(ordvalue)
				strs = "%s%s" % (strs,res)
			print strs
			print "---------------End of Data  ASCII-----------------\n"
		except Exception:
			excinfo=traceback.format_exc()
			print excinfo
			pass
 
if __name__ == '__main__':

	agent_hostname=lc_libs.lc_gethostname()
	
	#初始化
	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	
	ADDR=("0.0.0.0",1620)
	AgentList={}

	BUFSIZ=8192
	agents={}
	
	#程序处理
	try:
		#for line in open(confname):
		#	if line[0] == '#':
		#		continue
		#	else:
		#		lines=line.strip('\n').split("\t")
		#		if len(lines)<3:
		#			continue
		#		else:
		#			AgentList[lines[0]]={
		#				'agentip':lines[1],
		#				'agentport':int(lines[2]),
		#				'fathername':lines[3],
		#				'fatherip':lines[4],
		#				'fatherport':int(lines[5])
		#			}
		#			if lines[0]==agent_hostname:
		#				#ADDR=(str(lines[1],int(lines[2]))
		#				ADDR=("0.0.0.0",int(lines[2]))
						
		#server = SocketServer.ThreadingTCPServer(ADDR,LCAgent(agent_hostname,AgentList))
		server = SocketServer.ThreadingUDPServer(ADDR,LCAgent)
		#server=LCSocketServer(ADDR,LCAgent(agent_hostname,AgentList))
		#print dir(server)
		#server.InitArgvs(agent_hostname,AgentList)
		#server.InitAgentList()
		server.serve_forever()
	
	except Exception:
		#server.shutdown()
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" "+excinfo+"\n")
		logfile.flush()
		exit()
